#include "texteditor.h"

TextEditor::TextEditor(QWidget *parent) : QMainWindow(parent)
{
    textEdit = new QPlainTextEdit;
    setCentralWidget(textEdit);

    createActions();
    createMenus();
    createToolBars();
    createStatusBar();

    readSettings();

    connect(textEdit->document(), SIGNAL(contentsChanged()), this,
            SLOT(documentWasModified()));
    setCurrentFile("/vjjtUI/vjjtUI.cfg");
    setUnifiedTitleAndToolBarOnMac(true);
}

void TextEditor::closeEvent(QCloseEvent *event)
{
    if(maybeSave()){
        writeSettings();
        event->accept();
    }else{
        event->ignore();
    }
}

void TextEditor::newFile()
{
    if(maybeSave()){
        textEdit->clear();
        setCurrentFile("");
    }
}

void TextEditor::open()
{
    if(maybeSave()){
        QString fileName = QFileDialog::getOpenFileName(this);
        if(!fileName.isEmpty()){
            loadFile(fileName);
        }
    }
}

bool TextEditor::save()
{
    if(curFile.isEmpty())
        return saveAs();
    else
        return saveFile(curFile);
}

bool TextEditor::saveAs()
{
    QFileDialog dialog(this);
    dialog.setWindowModality(Qt::WindowModal);
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    QStringList files;
    if(dialog.exec())
        files = dialog.selectedFiles();
    else
        return false;
    return saveFile(files.at(0));
}

void TextEditor::about()
{
    QMessageBox::about(this, tr("About This Text Editor"),
                       tr("This <b>Text Editor</b> is a simple "
                          "Qt GUI application Created By Jeffery 20150824 "
                          "To learn Qt Programming! This is an example on the following website:<br>"
                          "http://doc.qt.io/qt-5/qtwidgets-mainwindows-application-example.html"));
}

void TextEditor::documentWasModified()
{
    setWindowModified(textEdit->document()->isModified());
}

void TextEditor::createActions()
{
    newAct = new QAction(QIcon(":/images/texteditor/new.png"),
                         tr("&New"), this);
    newAct->setShortcuts(QKeySequence::New);
    newAct->setStatusTip("Create a New File");
    connect(newAct, SIGNAL(triggered(bool)), this, SLOT(newFile()));

    openAct = new QAction(QIcon(":/images/texteditor/open.png"),
                          tr("&Open"), this);
    openAct->setShortcuts(QKeySequence::Open);
    openAct->setStatusTip("Open an Existing File");
    connect(openAct, SIGNAL(triggered(bool)), this, SLOT(open()));

    saveAct = new QAction(QIcon(":/images/texteditor/save.png"),
                          tr("&Save"), this);
    saveAct->setShortcuts(QKeySequence::Save);
    saveAct->setStatusTip("Save the Document to the disk");
    connect(saveAct, SIGNAL(triggered(bool)), this, SLOT(save()));

    saveAsAct = new QAction(tr("Save &As..."), this);
    saveAsAct->setShortcuts(QKeySequence::SaveAs);
    saveAct->setStatusTip("Save the document under a new name");
    connect(saveAsAct, SIGNAL(triggered(bool)), this, SLOT(saveAs()));

    exitAct = new QAction(tr("E&xit"), this);
    exitAct->setShortcuts(QKeySequence::Quit);
    exitAct->setStatusTip(tr("Exit this Application"));
    connect(exitAct, SIGNAL(triggered(bool)), this, SLOT(close()));

    cutAct = new QAction(QIcon(":/images/texteditor/cut.png"), tr("Cu&t"), this);
    cutAct->setShortcuts(QKeySequence::Cut);
    cutAct->setStatusTip("Cut the Current Selection's Contents "
                         "to the Clipboard");
    connect(cutAct, SIGNAL(triggered(bool)), textEdit, SLOT(cut()));

    copyAct = new QAction(QIcon(":/images/texteditor/copy.png"), tr("&Copy"), this);
    copyAct->setShortcuts(QKeySequence::Copy);
    copyAct->setStatusTip(tr("Copy the Selection's Contents "
                              "into the Current Clipboard"));
    connect(copyAct, SIGNAL(triggered(bool)), textEdit, SLOT(copy()));


    pasteAct = new QAction(QIcon(":/images/texteditor/paste.png"), tr("&Paste"), this);
    pasteAct->setShortcuts(QKeySequence::Paste);
    pasteAct->setStatusTip(tr("Paste the Clipboard's Contents "
                              "into the Current Selection"));
    connect(pasteAct, SIGNAL(triggered(bool)), textEdit, SLOT(paste()));

    aboutAct = new QAction(tr("&About"), this);
    aboutAct->setStatusTip("Show the Application About Box");
    connect(aboutAct, SIGNAL(triggered(bool)), this, SLOT(about()));

    aboutQtAct = new QAction(tr("About &Qt"), this);
    aboutQtAct->setStatusTip("Show the Qt's Library About Box");
    connect(aboutQtAct, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt()));

    cutAct->setEnabled(false);
    copyAct->setEnabled(false);
    connect(textEdit, SIGNAL(copyAvailable(bool)), cutAct,
            SLOT(setEnabled(bool)));
    connect(textEdit, SIGNAL(copyAvailable(bool)), copyAct,
            SLOT(setEnabled(bool)));
}

void TextEditor::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(newAct);
    fileMenu->addAction(openAct);
    fileMenu->addAction(saveAct);
    fileMenu->addAction(saveAsAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);

    editMenu = menuBar()->addMenu(tr("&Edit"));
    editMenu->addAction(cutAct);
    editMenu->addAction(copyAct);
    editMenu->addAction(pasteAct);

    menuBar()->addSeparator();

    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAct);
    helpMenu->addAction(aboutQtAct);
}

void TextEditor::createToolBars()
{
    fileToolBar = addToolBar(tr("File"));
    fileToolBar->addAction(newAct);
    fileToolBar->addAction(openAct);
    fileToolBar->addAction(saveAct);

    editToolBar = addToolBar(tr("Edit"));
    editToolBar->addAction(cutAct);
    editToolBar->addAction(copyAct);
    editToolBar->addAction(pasteAct);
}

void TextEditor::createStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}

void TextEditor::readSettings()
{
    QSettings settings("QtProject",
                       "A Simple Text Editor Application");
    QPoint pos = settings.value("pos",
                                QPoint(200,200)).toPoint();
    QSize size = settings.value("size",
                                QSize(400,400)).toSize();
    resize(size);
    move(pos);
}

void TextEditor::writeSettings()
{
    QSettings settings("QtProject",
                       "A Simple Text Editor Application");
    settings.setValue("pos", pos());
    settings.setValue("size", size());
}

bool TextEditor::maybeSave()
{
    if(textEdit->document()->isModified()){
        QMessageBox::StandardButton ret;
        ret = QMessageBox::warning(this, tr("Application"),
                           tr("This document has been modified!\n"
                              "Do you want to save your change?"),
                       QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if(ret == QMessageBox::Save)
            return save();
        else if(ret == QMessageBox::Cancel)
            return false;
    }
    return true;
}

void TextEditor::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        QMessageBox::warning(this, tr("Application"),
                             tr("Can not read file %1:\n"
                                "%2").arg(fileName)
                             .arg(file.errorString()));
        return;
    }
    QTextStream in(&file);
#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(Qt::WaitCursor);
#endif
    textEdit->setPlainText(in.readAll());
#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif
    setCurrentFile(fileName);
    statusBar()->showMessage(tr("File Loaded"), 2000);
}

bool TextEditor::saveFile(const QString &fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::WriteOnly | QFile::Text)){
        QMessageBox::warning(this, tr("Application"),
                            tr("Can not write file %1: %2")
                             .arg(fileName)
                             .arg(file.errorString()));
        return false;
    }
    QTextStream out(&file);
#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(Qt::WaitCursor);
#endif
    out << textEdit->toPlainText();
#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif
    setCurrentFile(fileName);
    statusBar()->showMessage(tr("File Saved"), 2000);
    return true;
}

void TextEditor::setCurrentFile(const QString &fileName)
{
    curFile = fileName;
    textEdit->document()->setModified(false);
    setWindowModified(false);

    QString shownName = curFile;
    if(curFile.isEmpty())
        shownName = "untitled.txt";
    setWindowFilePath(shownName);
}

QString TextEditor::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}


